#include <iostream>
#include <unistd.h>
#include <cstring>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>

int main(int argc, char* argv[]){
    if(argc != 2){
        std::cerr << "Usage: " << argv[0] << " <Port>" << std::endl;
        return 1;
    }
    uint64_t port = std::stoi(argv[1]); // 获取端口号

    // 1. 创建套接字
    int listen_sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(listen_sockfd < 0){
        perror("socket");
        return 1;
    }
    int opt = 1;
    setsockopt(listen_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); // 设置地址重用

    // 2. 绑定端口号
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));             // 初始化结构体
    addr.sin_family = AF_INET;                  // 地址族
    addr.sin_port = htons(port);                // 端口号，必须网络字节序
    // 使用 INADDR_ANY，表示监听所有可用的网络接口的连接
    addr.sin_addr.s_addr = htonl(INADDR_ANY);   // IP 地址，必须网络字节序
    if(bind(listen_sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0){
        perror("bind");
        close(listen_sockfd);
        return 1;
    }   
    // 3. 监听 -- backlog 最多连接数量设置
    if(listen(listen_sockfd, 10) < 0){
        perror("listen");
        close(listen_sockfd);
        return 1;
    }
    // 4. 连接 -- 接收客户端连接
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    // 阻塞等待连接
    int conn_sockfd = accept(listen_sockfd, (struct sockaddr*)&client_addr, &client_addr_len);
    if(conn_sockfd < 0){
        perror("accept");
        close(listen_sockfd);
        return 1;
    }

    char client_ip[INET_ADDRSTRLEN];
    // 将网络字节序的 IP 地址转换为点分十进制字符串
    inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, INET_ADDRSTRLEN);
    std::cout << "Client connected: " << client_ip << ":" << ntohs(client_addr.sin_port) << std::endl;

    // 5. 传输数据
    const char* message = "Hello, Client! This is the TCP Server";
    ssize_t bytes_send = send(conn_sockfd, message, strlen(message), 0);
    if (bytes_send > 0) {
        std::cout << "Sent " << bytes_send << " bytes to client: " << message << std::endl;
    } else if (bytes_send == 0) {
        std::cout << "Connection closed by client." << std::endl;
    } else {
        perror("send");
    }

    // 6. 关闭
    close(listen_sockfd);
    close(conn_sockfd); 
    return 0;
}